import { Component, State, Watch, h } from '@stencil/core'

@Component({
  tag: 'popup-root',
  styleUrl: 'popup-root.css',
  shadow: false,
})
export class PopupRoot {
  private link = 'https://github.com/guocaoyi/create-chrome-ext'

  @State() count: number = 0

  @Watch('count')
  watchPropHandler(newValue: boolean) {
    chrome.storage.sync.set({ count: newValue })
    chrome.runtime.sendMessage({ type: 'COUNT', count: newValue })
  }

  componentWillLoad() {
    chrome.storage.sync.get(['count'], (result) => {
      this.count = result.count || 0
    })
  }

  minus = () => {
    if (this.count > 0) this.count--
  }

  add = () => {
    this.count++
  }

  render() {
    return (
      <main>
        <h3>Popup Page</h3>
        <div class="calc">
          <button onClick={this.minus} disabled={this.count <= 0}>
            -
          </button>
          <label>{this.count}</label>
          <button onClick={this.add}>+</button>
        </div>
        <a href={this.link} target="_blank">
          generated by create-chrome-ext
        </a>
      </main>
    )
  }
}
